#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import COOPGIS_Ajax, COOPGIS_FormMisc, COOPGIS_FormGeography, COOPGIS_FormAssembly, COOPGIS_GPS, COOPGIS_Misc
import COOPGIS_DynamicTemplate, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms
from django.db import transaction


def WriteAssemblyEditorStatus(String):  
    File=open(djangoproject.settings.COOPGISAssemblyEditorLogFileName, 'a')
    File.write(str(datetime.datetime.now()) + ':   ' + String + '\n')
    File.close()




def AssemblyEditor(request):
    ApplicationName=djangoproject.settings.COOPGISAssemblyEditorApplicationName
    UserNameOrIPAddress, DefaultMap=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName) 
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap)
    if(not applicationPermission):  #Show view of Map and Form if no Permissions, do not perform any form processing
        MapFileName, LayerName=COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress) 
        OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(None, None)   
        t = loader.get_template('/opt/coopgis/djangoproject/templates/assemblyeditor.html')
        c = Context({'OpenLayersZoom': OpenLayersZoom, 'AssemblyEditorForm': form,
                     'MapFileName': MapFileName, 'LayerName': LayerName, 'LoginStatus':LoginStatus})
        return HttpResponse(t.render(c))
    SelectionStation=SelectionSpan=GPSStatus2=''
    COOPGIS_FormGeography.GetAndSetDefaultMap(form, ApplicationName, UserNameOrIPAddress)
    SelectionStation, SelectionSpan, GPSStatus=COOPGIS_FormGeography.SetSelectionStationAndSpan(form)
    SelectionStation, SelectionSpan, GPSStatus2=COOPGIS_FormGeography.CreateStation(form, SelectionStation, SelectionSpan, UserNameOrIPAddress)
    
    SelectionSpan=COOPGIS_FormGeography.CreateSpan(form, SelectionStation, SelectionSpan, UserNameOrIPAddress)
    COOPGIS_FormGeography.UpdateStationComment(form, SelectionStation, UserNameOrIPAddress)
    COOPGIS_FormGeography.UpdateStationTransformerBankType(form, SelectionStation, UserNameOrIPAddress)

    COOPGIS_FormGeography.UpdateSpanComment(form, SelectionSpan, UserNameOrIPAddress)
    GPSStatus3, SelectionStation = COOPGIS_FormGeography.MoveStation(form, SelectionStation, UserNameOrIPAddress)
    if(not SelectionStation and not SelectionSpan):
        Zoom=15
    else:
        Zoom=23
    OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(SelectionStation, SelectionSpan, Zoom=Zoom)  #Get the Zoom before the span is deleted so area is not left on this refresh    
    NumberOfStationAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfStationAssembliesListedOnForm(SelectionStation)
    NumberOfSpanAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfSpanAssembliesListedOnForm(SelectionSpan)

    COOPGIS_FormGeography.DeleteStation(form, SelectionStation, UserNameOrIPAddress)
    COOPGIS_FormGeography.DeleteURDMarker(form, SelectionStation)
    COOPGIS_FormGeography.DeleteSpan(form, SelectionSpan, UserNameOrIPAddress)
    for assemblyFormNumber in range(0, NumberOfStationAssembliesListedOnForm + 1):
        COOPGIS_FormAssembly.ProcessStationAssembly(form, assemblyFormNumber, SelectionStation, UserNameOrIPAddress, UpdateStakerWorkOrderIndicator=False)
    for assemblyFormNumber in range(0, NumberOfSpanAssembliesListedOnForm + 1):
        COOPGIS_FormAssembly.ProcessSpanAssembly(form, assemblyFormNumber, SelectionSpan, UserNameOrIPAddress, UpdateStakerWorkOrderIndicator=False)
    #Now the Form Has been processed, it needs to be dynamically rebuilt to reflect the new number of Assemblies at the station and span

    NumberOfStationAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfStationAssembliesListedOnForm(SelectionStation)
    NumberOfSpanAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfSpanAssembliesListedOnForm(SelectionSpan)
    NewForm=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap, station=SelectionStation, span=SelectionSpan)
    NewForm=COOPGIS_FormAssembly.CopyPreviousFormInformation(form, NewForm)
    form=NewForm

    COOPGIS_FormMisc.PopulateMiscFormFields(form)
    COOPGIS_FormAssembly.PopulateStationAssemblies(form, SelectionStation, NumberOfStationAssembliesListedOnForm)
    COOPGIS_FormAssembly.PopulateSpanAssemblies(form, SelectionSpan, NumberOfSpanAssembliesListedOnForm)
    COOPGIS_Misc.UpdateSelection(SelectionStation, SelectionSpan, UserNameOrIPAddress)
    StationAssemblyList, SpanAssemblyList = COOPGIS_Misc.GetNearbyInfo(SelectionStation, SelectionSpan)
    COOPGIS_DynamicTemplate.UpdateAssemblyEditorTemplate(NumberOfStationAssembliesListedOnForm, NumberOfSpanAssembliesListedOnForm, UserNameOrIPAddress)
    
    if(SelectionStation):
        TransformerBanks=TransformerBank.objects.filter(Station=SelectionStation).order_by('id')
    else:
        TransformerBanks=[]

    MapFileName, LayerName =COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/assemblyeditor' + UserNameOrIPAddress + '.html')
    c = Context({'OpenLayersZoom': OpenLayersZoom, 'form': form,
                 'LoginStatus':LoginStatus, 'MapFileName': MapFileName, 'LayerName': LayerName,
                 'GPSStatus':GPSStatus, 'GPSStatus2': GPSStatus2, 'GPSStatus3': GPSStatus3,
                 'StationAssemblyList': StationAssemblyList, 'SpanAssemblyList': SpanAssemblyList,
                 'ServerIndicator': djangoproject.settings.COOPGISServerIndicator, 'TransformerBanks': TransformerBanks})
    return HttpResponse(t.render(c))

